package com.zwh.config;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.boot.web.servlet.ServletComponentScan;

import java.io.IOException;

@ServletComponentScan
@WebFilter(urlPatterns = {"/appointment","/departments"})//过滤器
public class ServletFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 获取当前Session
        HttpSession session = httpRequest.getSession(false);

        // 检查用户是否已登录
        if (session == null || session.getAttribute("username") == null) {
            // 用户未登录，重定向到登录页面
            // 返回一个 HTML 页面，包含弹窗和重定向
            String alertScript = "<script>alert('请先登录！'); window.location.href='homeb';</script>";
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(alertScript);
            return;
        }

        // 用户已登录，继续请求处理链
        chain.doFilter(request, response);
    }
}
